﻿//利用jquery.validate的控件验证
function JQueryValidate(controls, controlSets) {
    this.Controls = controls;
    var defaultControlSets = { CurrentForm: "form1", ErrClass: "error", ValidClass: "valid", ErrorElement: "div", PlacementType: "", OKMsg: "" };
    this.ControlSets = jQuery.extend(defaultControlSets, controlSets);
}
JQueryValidate.prototype.Initial = function () {
    var controlInfo = this;
    var controls = this.Controls;
    var controlSets = this.ControlSets;

    var validator = $("#" + controlSets.CurrentForm).validate({
        debug: false,
        onkeyup: false,
        onsubmit: false,
        errorElement: controlSets.ErrorElement,
        errorClass: controlSets.ErrClass,
        validClass: controlSets.ValidClass,
        rules: {},
        messages: {},
        showErrors: controlSets.ShowErrors,
        unhighlight: controlSets.Unhighlight,
        errorPlacement: controlSets.ErrorPlacement != null ? controlSets.ErrorPlacement : (controlSets.PlacementType == "" ? undefined : function (error, element) {  //验证消息放置的地方
            error.appendTo(GetErrorPlacement(element, controlSets.PlacementType));
        }),

        errorPlacement: controlSets.PlacementType == "" ? undefined : function (error, element) {  //验证消息放置的地方
            error.appendTo(GetErrorPlacement(element, controlSets.PlacementType));
        },
        success: controlSets.OKMsg == "" ? undefined : function (label) {
            label.addClass(controlSets.ValidClass).text(controlSets.OKMsg); //由于控件类库不支持每个控件有不同的提示，则改为统一提示，或者直接把success改为类名
        }
    });
    this.Validator = validator;

    $.each(controls, function (i) {
        controlInfo.AddRule(controls[i].Name, controls[i].Rules, controls[i].Messages);
    });

    jQuery.validator.addMethod("isTel", function (value, element) {
        var tel = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
        return this.optional(element) || (tel.test(value));
    }, "请正确填写您的电话号码");

    jQuery.validator.addMethod("isNumber", function (value, element) {
        return this.optional(element) || (!isNaN(value));
    }, "请输入数字");

    jQuery.validator.addMethod("isMobile", function (value, element) {
        var tel = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(14[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
        return this.optional(element) || (tel.test(value));
    }, "请正确填写您的手机号码");

    jQuery.validator.addMethod("stringCheck", function (value, element) {
        return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
    }, "只能输入中文字、英文字母、数字和下划线");

    jQuery.validator.addMethod("charnum", function (value, element) {
        var chrnum = /^([a-zA-Z0-9]+)$/;
        return this.optional(element) || (chrnum.test(value));
    }, "只能输入数字和字母(字符A-Z, a-z, 0-9)");

    jQuery.validator.addMethod("isChineseAndEnglish", function (value, element) {
        var reg = /[^\a-\z\A-\Z\u4E00-\u9FA5]/g;
        return this.optional(element) || (!reg.test(value));
    }, "只能输入中文与英文");

    jQuery.validator.addMethod("checkChinese", function (value, element) {
        var reg = /[^\u4E00-\uFFFF0\x2D-\x2F\x28-\x29]/g;
        return this.optional(element) || (!reg.test(value));
    }, "只能输入中文()");

    jQuery.validator.addMethod("isWebsite", function (value, element) {
        var regWebsite = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
        return this.optional(element) || (regWebsite.test(value));
    }, "网站地址格式不正确");

    jQuery.validator.addMethod("stringlength", function (value, element, param) {
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) || (length == param);
    }, "请确保输入值的长度等于{0}字节(一个中文字算2个字节)");

    jQuery.validator.addMethod("byteRangeLength", function (value, element, param) {
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) || (length >= param[0] && length <= param[1]);
    }, "请确保输入值的长度在{0}-{1}个字节之间(一个中文字算2个字节)");
}
JQueryValidate.prototype.AddRule = function(key, ruels, message) {
    var controlInfo = this;
    controlInfo.Validator.settings.rules[key] = jQuery.validator.normalizeRule(ruels);
    controlInfo.Validator.settings.messages[key] = message;
}
JQueryValidate.prototype.RemoveRule = function(key) {
    var controlInfo = this;
    controlInfo.Validator.settings.rules[key] = {};
    controlInfo.Validator.settings.messages[key] = {};
}
JQueryValidate.prototype.Check = function() {
    var controlInfo = this;
    controlInfo.Validator.prepareForm();
    $.each(controlInfo.Controls, function(i) {
        var element = controlInfo.Validator.findByName(controlInfo.Controls[i].Name)[0];
        if (element && $(element).is(':visible')) controlInfo.Validator.check(element);
    });
    controlInfo.Validator.showErrors();
    return controlInfo.Validator.valid();
}

//扩展JQueryValidate验证
function ControlValidation(controls, controlSets, errorControlSet) {
    this.Controls = controls; alert
    var defaultControlSets = { CurrentForm: "form1", ErrClass: "error", ValidClass: "valid", ErrorElement: "div", NormalClass: "errMsgGreen", PlacementType: "", SugClass: "", CompleteClass: "", OKMsg: "" };
    this.ControlSets = jQuery.extend(defaultControlSets, controlSets);
    this.ErrorControl = new ErrorControl(errorControlSet);

    this.JQueryValidate = new JQueryValidate(controls, { CurrentForm: this.ControlSets.CurrentForm, ErrClass: this.ControlSets.ErrClass, ValidClass: this.ControlSets.ValidClass, ErrorElement: this.ControlSets.ErrorElement, PlacementType: this.ControlSets.PlacementType, OKMsg: this.ControlSets.OKMsg });
    this.JQueryValidate.Initial();
}
ControlValidation.prototype.Initial = function() {
    var controlInfo = this;
    var controls = this.Controls;
    var controlSets = this.ControlSets;
    var errorControl = this.ErrorControl;

    $.each(controls, function(i) {
        var element = controlInfo.GetByName(controls[i].Name)[0];
        var sugMessage = controlInfo.GetControlMessage(element, "Msg");
        if (sugMessage != "")
            errorControl.GetErrorControl(element, controlSets.NormalClass, sugMessage).show();

        $(element).focus(function() {
            sugMessage = controlInfo.GetControlMessage(element, "SugMsg");
            if (sugMessage != "")
                errorControl.GetErrorControl(element, controlSets.SugClass, sugMessage).show();
        })
        .blur(function() {
            errorControl.GetErrorControl(element, "", "").hide();
        });
    });
}

ControlValidation.prototype.GetControlMessage = function(element, messageType) {
    var controls = this.Controls;
    var message = "";
    $.each(controls, function(i) {
        if (controls[i].Name == element.name && controls[i][messageType] != undefined) {
            message = controls[i][messageType];
        }
    });
    return message;
}
ControlValidation.prototype.Check = function() {
    var controlInfo = this;
    var errorControl = this.ErrorControl;
    $.each(controlInfo.Controls, function(i) {
        var element = controlInfo.GetByName(controlInfo.Controls[i].Name)[0];
        errorControl.GetErrorControl(element, "", "").hide();
    });
    return this.JQueryValidate.Check();
}
//根据“name”或者id获取控件
ControlValidation.prototype.GetByName = function(elementName) {
    if ($(document.getElementsByName(elementName)).length > 0)
        return $(document.getElementsByName(elementName));
    else
        return $(document.getElementById(elementName));
}


//错误控件
function ErrorControl(errorSets) {
    var defaultSets = { RelType: "", RelWord: "Err", TagName: "div", PlacementType: "" };
    this.ControlSets = jQuery.extend(defaultSets, errorSets);
}
//获取错误控件
ErrorControl.prototype.GetErrorControl = function(element, className, message) {
    var controlInfo = this;
    var controlSets = this.ControlSets;
    var name = controlInfo.GetIdOrName(element);
    var errorPlacement = GetErrorPlacement(element, controlSets.PlacementType);

    var errControl = undefined;
    if (controlSets.RelType == "IdSuffix") //主控件加后缀(RelWord)
    {
        errControl = $("#" + name + controlSets.RelWord);
        errControl = controlInfo.AddErrorControl(element, errControl, errorPlacement, controlSets.TagName).attr({ "id": name + controlSets.RelWord });
    }
    else if (controlSets.RelType == "NextAll") //位于主控件后的标签，要确保只有一个错误标签
    {
        if (errorPlacement == null || errorPlacement == undefined)
            errControl = $(element).nextAll(controlSets.TagName).filter(function() { return $(this).attr('forSelf') == name; }); //如果关联控件的“forSelf”属性和主控件编号一致，优先使用
        else
            errControl = errorPlacement.children().filter(function() { return $(this).attr('forSelf') == name; });

        if (errControl == undefined || errControl.length == 0)
            errControl = $(element).nextAll(controlSets.TagName);
        errControl = controlInfo.AddErrorControl(element, errControl, errorPlacement, controlSets.TagName).attr({ "forSelf": name });
    }
    else if (controlSets.RelType == "Attribute") {  //主控件属性(RelWord)作为错误控件的Id
        if ($(element).attr(controlSets.RelWord) != undefined && $(element).attr(controlSets.RelWord) != "") {
            errControl = $("#" + $(element).attr(controlSets.RelWord));
            errControl = controlInfo.AddErrorControl(element, errControl, errorPlacement, controlSets.TagName).attr({ "id": $(element).attr(controlSets.RelWord) });
        }
    }
    else {
        if (errorPlacement == null || errorPlacement == undefined)
            errControl = $(element).nextAll(controlSets.TagName).filter(function() { return $(this).attr('forSelf') == name; });
        else
            errControl = errorPlacement.children().filter(function() { return $(this).attr('forSelf') == name; });

        errControl = controlInfo.AddErrorControl(element, errControl, errorPlacement, controlSets.TagName).attr({ "forSelf": name });
    }

    if (errControl == undefined) {
        WinAlert("提示信息", "错误控件定义错误或配置错误");
    }
    return errControl.removeClass().addClass(className).html(message);
}
//如果错误控件不存在，创建错误控件，否则返回错误控件
ErrorControl.prototype.AddErrorControl = function(element, errControl, errorPlacement, tagName) {
    if (errControl == undefined || errControl.length == 0) {
        errControl = $("<" + tagName + "/>");
        if (errorPlacement == null || errorPlacement == undefined)
            errControl.insertAfter(element);
        else
            errControl.appendTo(errorPlacement);
    }
    return errControl;
}
//如果Id不为空，返回Id号，否则返回“name”属性
ErrorControl.prototype.GetIdOrName = function(element) {
    if ($(element).attr("id") == undefined || $(element).attr("id") == "")
        return $(element).attr("name");
    else
        return $(element).attr("id");
}

//获取错误控件容器
function GetErrorPlacement(element, placementType) {
    if (placementType == "ParentNextTd")
        return $(element).parent("td").next("td");
    else if (placementType == "ParentNextDiv")
        return $(element).parent("div").next("div");
    else if (placementType == "NextDiv")
        return $(element).nextAll("div");
    else if (placementType == "NextSpan")
        return $(element).nextAll("span");
    else
        return undefined;
}